interface BCEventInterface{
	cb: (sendData?: any)=>void,
	target: any
}

export class BCNotificationCenter {
	private static m_instance: BCNotificationCenter = null;

	private m_eventListMap: Map<string, BCEventInterface[]> = new Map();

	private constructor(){};

	static get instance(){
		if(!this.m_instance){
			this.m_instance = new BCNotificationCenter();
		}
		return this.m_instance;
	}

	/**
	 * 注册监听
	 * name 事件名称
	 * cb 回调
	 * target
	 */
	onEvent(name: string, cb: (sendData?: any, ...optionalParams: any[]) => void, target:any){
		let eventList = this.m_eventListMap.get(name);
		if (!eventList){
			eventList = [];
		}
		eventList.push({ cb: cb, target: target });
		this.m_eventListMap.set(name, eventList);
	}

	/**
	 * 发送通知
	 * name 事件名称
	 * sendData 需要发送的参数
	 */
	emitEvent(name: string, sendData?: any, ...optionalParams: any[]){
		let list = this.m_eventListMap.get(name);
		if(!list){
			return;
		}

		for (let i = list.length - 1; i >= 0; i--) {
			let event = list[i];
			event && event.cb.call(event.target, sendData, ...optionalParams);
		}
	}

	/**
	 * 关闭监听
	 * name 事件名称
	 * target
	 */
	offEvent(name: string, target?: any){
		if(!target){
			this.m_eventListMap.delete(name);
		} else {
			let list = this.m_eventListMap.get(name); 
			if(!list){
				return;
			}
			for(let i:number=0,count:number=list.length; i<count; i++){
				if(list[i].target === target){
					list.splice(i, 1);
					break;
				}
			}
			this.m_eventListMap.set(name, list); 
		}
	}

	/**
	 * 清空所有监听
	 */
	offAllEvent(target?: any){
		if(!target){
			this.m_eventListMap.clear();
			return;
		}
		this.m_eventListMap.forEach((eventList, name)=>{
			if(!eventList || eventList.length == 0){
				return;
			}
			for (let i: number = 0, count: number = eventList.length; i < count; i++) {
				if (eventList[i].target === target) {
					eventList.splice(i, 1);
					break;
				}
			}
			this.m_eventListMap.set(name, eventList); 
		});
	}

	/**
	 * 通过名称清空监听
	 */
	offEventWithName(name: string){
		this.m_eventListMap.delete(name);
	}
}
